import { Injectable, NestInterceptor, CallHandler, ExecutionContext } from '@nestjs/common'
import { map } from 'rxjs/operators'
import { Observable } from 'rxjs'
import { Request } from 'express'
import { tap } from 'rxjs/operators';
import { Logger } from '../middleware/log/index'
interface data<T> { data: T }

@Injectable()
export class GlobalInterceptor<T = any> implements NestInterceptor {
    intercept(context: ExecutionContext, next: CallHandler): Observable<data<T>> {
        const start = Date.now(); // 请求开始时间
        const host = context.switchToHttp();
        // 获取请求报文
        const req = host.getRequest<Request>();
        return next.handle().pipe(map(data => {
            return !!data?.status ? data : {
                data, status: 200, message: data?.message || ""
            }
        }), tap((...argus) => {
            var now = Date.now();
            // 请求地址，方法，参数，ua, ip, 接口耗时
            let accessRow = `url: ${req.url} | method: ${req.method} | ua: ${req.headers['user-agent']}  | ip: ${req.ip} | apiTime: ${now - start}ms`;
            Logger.access(accessRow);
        }));
    }
}